package com.zhuhjay.ruiji.controller;

import com.zhuhjay.ruiji.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @author ZhuHJay
 * @date 2022/5/16 17:20
 */
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${ruiji.path}")
    private String path;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        if( file.isEmpty() ){
            return R.error("上传的文件不能为空");
        }
        File loadPath = new File(path);
        if( !loadPath.exists() ){
            loadPath.mkdirs();
        }
        String originalFilename = file.getOriginalFilename();
        String suf = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString();
        try {
            file.transferTo(new File(path + fileName + suf));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName + suf);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            FileInputStream fileInputStream = new FileInputStream(new File(path + name));

            ServletOutputStream outputStream = response.getOutputStream();

            int len = 0;
            byte[] bytes = new byte[1024];
            while( (len = fileInputStream.read(bytes)) != -1 ){
                outputStream.write(bytes);
                outputStream.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
